from html import escape
from typing import Any, Dict, List, Tuple


def _format_cost_ns(value: Any) -> Tuple[str, str]:
    if isinstance(value, (int, float)):
        return f"{int(value)}", f"{value / 1_000_000:.2f}"
    return "N/A", "N/A"


def _format_cost_ms(value: Any) -> str:
    if isinstance(value, (int, float)):
        return f"{value / 1_000_000:.2f}"
    return "N/A"


def render_phase_table(rows: List[Dict[str, Any]], title: str = "阶段耗时分层表") -> str:
    if not rows:
        return ""
    header = """
        <tr>
            <th>层级</th>
            <th>阶段名称</th>
            <th>耗时(ns)</th>
            <th>耗时(ms)</th>
        </tr>
    """
    body_rows = []
    for row in rows:
        cost_ns_text, cost_ms_text = _format_cost_ns(row.get("cost"))
        indent_px = max(row.get("level", 1) - 1, 0) * 18
        raw_name = row.get("name", "")
        label = escape(raw_name).replace("\n", "<br>").replace("|", "<br>")
        if row.get("has_more"):
            label += ' <span class="phase-more">…</span>'
        name_cell = f'<td class="phase-name" style="padding-left:{indent_px}px">{label}</td>'
        body_rows.append(
            f"""
            <tr>
                <td>{row.get("path", "")}</td>
                {name_cell}
                <td>{cost_ns_text}</td>
                <td>{cost_ms_text}</td>
            </tr>
            """
        )
    return f"""
        <div class="phase-table-wrapper">
            <h3>{title}</h3>
            <div class="table-scroll">
                <table class="phase-table">
                    {header}
                    {''.join(body_rows)}
                </table>
            </div>
        </div>
    """


def render_callstack_table(rows: List[Dict[str, Any]], title: str = "调用栈明细") -> str:
    if not rows:
        return ""
    header = """
        <tr>
            <th>层级</th>
            <th>函数名</th>
            <th>耗时(ms)</th>
            <th>占比(%)</th>
        </tr>
    """
    body_rows = []
    for row in rows:
        level = row.get("level", 0)
        raw_name = row.get("name", "")
        label = escape(raw_name).replace("\n", "<br>")
        if row.get("is_other"):
            label += ' <span class="phase-other-tag">other</span>'
        indent_px = max(level - 1, 0) * 18
        cost_ms = _format_cost_ms(row.get("cost"))
        percent = row.get("percent")
        percent_text = f"{percent:.2f}%" if isinstance(percent, (int, float)) else "N/A"
        body_rows.append(
            f"""
            <tr>
                <td>{level}</td>
                <td style="padding-left:{indent_px}px">{label}</td>
                <td>{cost_ms}</td>
                <td>{percent_text}</td>
            </tr>
            """
        )
    return f"""
        <div class="card">
            <h2>{title}</h2>
            <div class="table-scroll">
                <table class="stage-table callstack-table">
                    {header}
                    {''.join(body_rows)}
                </table>
            </div>
        </div>
    """


def render_hotspot_table(rows: List[Dict[str, Any]], title: str = "热点函数耗时TOP") -> str:
    if not rows:
        return ""
    header = """
        <tr>
            <th>函数名</th>
            <th>耗时(ms)</th>
            <th>占比(%)</th>
        </tr>
    """
    body_rows = []
    for row in rows:
        raw_name = row.get("name", "")
        name = escape(raw_name).replace("\n", "<br>")
        cost_text = _format_cost_ms(row.get("cost"))
        percent = row.get("percent")
        percent_text = f"{percent:.2f}%" if isinstance(percent, (int, float)) else "N/A"
        body_rows.append(
            f"""
            <tr>
                <td>{name}</td>
                <td>{cost_text}</td>
                <td>{percent_text}</td>
            </tr>
            """
        )
    return f"""
        <div class="card">
            <h2>{title}</h2>
            <div class="table-scroll">
                <table class="stage-table hotspot-table">
                    {header}
                    {''.join(body_rows)}
                </table>
            </div>
        </div>
    """
